package com.slipper.common.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.slipper.constants.Constants;
import com.slipper.core.file.FileServiceUtil;
import com.slipper.core.gson.GsonUtil;
import com.slipper.system.affix.bo.AffixItemBO;
import com.slipper.system.affix.service.AffixItemService;
import com.slipper.system.setting.bo.SettingBO;
import com.slipper.util.*;
import com.slipper.system.setting.service.SettingService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import javax.imageio.ImageIO;

import jakarta.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;

@RestController
@RequestMapping
public class CommonController {
    private final char[] codeSequence = {'A', 'B', 'D', 'E', 'F', 'G',
            'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
            'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4',
            '5', '6', '7', '8', '9'};
    @Resource
    private SettingService settingService;
    @Resource
    private AffixItemService affixItemService;

    @PostMapping("/refresh")
    public String refresh() {
        Constants.getCurrentUser();
        return ResultUtil.successResult("刷新成功！");
    }

    /**
     * 图片下载
     */
    @GetMapping("/image/{id}")
    public void image(HttpServletResponse response, @PathVariable("id") String id) throws Exception {
        if (Tool.isBlank(id)) return;

        AffixItemBO affixItem = this.affixItemService.queryBy(id);
        if (affixItem == null) {
            affixItem = this.affixItemService.queryByAffixId(id);
        }
        if (affixItem == null) return;

        FileUtil.download(response, affixItem.getTrueName(), FileServiceUtil.readFile(affixItem.getSavePath()));
    }

    @GetMapping("/video/{id}")
    public void video(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable("id") String id) throws Exception {
        if (Tool.isBlank(id)) return;

        AffixItemBO affixItem = this.affixItemService.queryBy(id);
        if (affixItem == null) {
            affixItem = this.affixItemService.queryByAffixId(id);
        }
        if (affixItem == null) return;

        response.reset();
        FileServiceUtil.readFile(affixItem.getSavePath(), request.getHeader("Range"), response);
    }

    @PostMapping(value = "/setting")
    public String setting() {
        SettingBO setting = settingService.querySetting();
        String json = GsonUtil.toJson(setting);
        String key = Tool.randomString(16);
        String sha = Tool.randomString(16);

        Map<String, String> result = new HashMap<>();
        result.put("token", AESUtil.encrypt(json, key));
        result.put("sha", key + sha);
        return ResultUtil.successResult(null, result);
    }

    @RequestMapping(value = "/captcha")
    public void captcha(HttpServletResponse response) throws Exception {
        // 验证码图片的宽度。
        int width = 80;
        // 验证码图片的高度。
        int height = 32;
        // 验证码字符个数
        int codeCount = 4;
        // 字体高度
        int fontHeight = height + 2;
        int x = width / (codeCount + 1) + 2;
        int y = height - 4;

        // 定义图像buffer
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        // 创建一个随机数生成器类
        Random random = new Random();
        // 将图像填充为白色
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, width, height);
        // 创建字体，字体的大小应该根据图片的高度来定。
        Font font = new Font("Arial", Font.BOLD, fontHeight);
        // 设置字体。
        g.setFont(font);
        // 画边框。
        g.setColor(new Color(174, 198, 224));
        g.drawRect(0, 0, width - 1, height - 1);
        // 线条
        g.setColor(new Color(5, 108, 175));
        // 随机产生160条干扰线，使图象中的认证码不易被其它程序探测到。
        for (int i = 0; i < 60; i++) {
            int lx = random.nextInt(width);
            int ly = random.nextInt(height);
            int xl = random.nextInt(30);
            int yl = random.nextInt(30);
            g.drawLine(lx, ly, lx + xl, ly + yl);
        }
        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
        StringBuilder randomCode = new StringBuilder();
        int red, green, blue;
        // 随机产生codeCount数字的验证码。
        for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字。
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            // 用随机产生的颜色将验证码绘制到图像中。
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, i * x + 2, y);
            // 将产生的四个随机数组合在一起。
            randomCode.append(strRand);
        }
        Constants.setCaptcha(randomCode.toString());
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png;charset=UTF-8");
        ImageIO.write(buffImg, "jpeg", response.getOutputStream());
    }

    @PostMapping(value = "/qrcode")
    public void qrcode(HttpServletResponse response, @RequestBody Map<String, Object> paramMap) throws Exception {
        String message = (String) paramMap.get("message");
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix matrix = new QRCodeWriter().encode(message, BarcodeFormat.QR_CODE, 200, 200, hints);

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png;charset=UTF-8");
        MatrixToImageWriter.writeToStream(matrix, "jpeg", response.getOutputStream());
    }
}
